package com.ygqh.baby.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.ygqh.baby.annotation.WebLog;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.HttpUtil;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.MessageType;
import com.ygqh.baby.ao.PlatformType;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.model.ChatRecord;
import com.ygqh.baby.model.CustomerUser;
import com.ygqh.baby.model.YgOrderInfoModel;
import com.ygqh.baby.model.YgOrderModel;
import com.ygqh.baby.model.YgReturnOrderInfoModel;
import com.ygqh.baby.model.YgReturnOrderModel;
import com.ygqh.baby.model.YgUserModel;
import com.ygqh.baby.po.YgReturnOrderLog;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.ChatRecordService;
import com.ygqh.baby.service.CustomerUserService;
import com.ygqh.baby.service.QuickReplyService;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.service.YgReturnOrderLogService;
import com.ygqh.baby.service.YgReturnOrderService;

@RestController
@RequestMapping("/chat/user")
public class YgUserController extends BaseController {

	@Autowired
	private ChatRecordService chatRecordService;
	@Autowired
	private CustomerUserService customerUserService;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private QuickReplyService quickReplyService;
	@Autowired
	private YgReturnOrderService ygReturnOrderService;
	@Autowired
	private YgReturnOrderLogService ygReturnOrderLogService;
	@Autowired
	private RedisDao redisDao;

	/**
	 * 获取用户聊天记录
	 *
	 * @param queryInfo
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findUserRecordList")
	@ResponseBody
	public JSONPObject findUserRecordList(QueryInfo queryInfo, String callback) {
		return new JSONPObject(callback,
				Message.success(chatRecordService.findUserRecordList(Arrays.asList(getSessionUser().getId()), null, queryInfo)));
	}

	/**
	 * 保存用户发送的信息
	 *
	 * @param detailContent
	 * @param messageType
	 * @param customerId
	 * @param callback
	 * @return
	 */
	@WebLog("保存用户发送的信息")
	@RequestMapping("/saveUserRecord")
	@ResponseBody
	public JSONPObject saveUserRecord(String detailContent, String originalImage, MessageType messageType, String customerId, String callback) {
		YgUserModel sessionUser = getSessionUser();
		logger.info("保存用户发送的信息，userId： --->" + sessionUser.getId());
		CustomerUser customerUser;
		if (StringUtils.isNotBlank(customerId)) {
			customerUser = customerUserService.findUserById(customerId);
		} else {
			customerUser = customerUserService.findCustomerByDefault();
			if (customerUser == null) {
				customerUser = new CustomerUser();
				customerUser.setNickName("留言信息");
			}
		}
		logger.info("保存用户发送的信息, userId： --->" + sessionUser.getId() + ", customer --> " + customerUser.getTrueName());
		ChatRecord chatRecord = new ChatRecord();
		chatRecord.setDetailContent(detailContent);
		chatRecord.setOriginalImage(originalImage);
		chatRecord.setCreateTime(new Date());
		chatRecord.setMessageType(messageType);
		chatRecord.setReceiveHeadId(customerUser.getHeadFileId());
		chatRecord.setReceiveNickName(StringUtils.isNotBlank(customerUser.getTrueName()) ? customerUser.getTrueName() : customerUser.getNickName());
		chatRecord.setReceiveUserId(customerUser.getId());
		chatRecord.setUserId(sessionUser.getId());
		chatRecord.setUserNickName(sessionUser.getNickName());
		chatRecord.setSendHeadId(sessionUser.getHeadFileId());
		chatRecord.setSendNickName(sessionUser.getNickName());
		chatRecord.setSendUserId(sessionUser.getId().toString());
		chatRecordService.save(chatRecord);
		//异步发送消息推送给在线客服		
		String msg = sessionUser.getNickName() + "说:" + detailContent;
		if (!chatRecord.getMessageType().equals(MessageType.Text))
			msg = sessionUser.getNickName() + "发送了一个" + chatRecord.getMessageType().getTitle();
		try {
			sendAppMessage(customerId, msg);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger.info("保存用户发送的信息成功");
		return new JSONPObject(callback, Message.success(chatRecord));
	}

	/**
	 * 更新消息已读
	 *
	 * @param recordId
	 * @param callback
	 * @return
	 */
	@WebLog("更新消息已读")
	@RequestMapping("/readRecord")
	@ResponseBody
	public JSONPObject readRecord(String callback) {
		return new JSONPObject(callback, chatRecordService.updateChatRecordToRead(null, getSessionUser().getId().toString(), getSessionUser()));
	}

	/**
	 * 为当前用户分配客服
	 *
	 * @param callback
	 * @return
	 */
	@WebLog("为当前用户分配客服")
	@RequestMapping("/distributionCustomerToUser")
	@ResponseBody
	public JSONPObject distributionCustomerToUser(String callback, String onlineCustomerId, PlatformType platformType) {
		YgUserModel sessionUser = getSessionUser();
		sessionUser.setPlatformType(platformType == null ? PlatformType.H5 : platformType);
		return new JSONPObject(callback, customerUserService.distributionCustomerToUser(sessionUser, onlineCustomerId));
	}

	/**
	 * 获取用户全部有效订单
	 *
	 * @param userId
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findOrderList")
	@ResponseBody
	public JSONPObject findOrderListByUserId(String callback) {
		List<YgOrderModel> orderList = ygOrderService.findOrderList(getSessionUser().getId());
		JSONPObject json = new JSONPObject(callback, Message.success(orderList));
		return json;
	}

	/**
	 * 获取订单详情
	 *
	 * @param orderId
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findOrderInfo")
	@ResponseBody
	public JSONPObject findOrderInfo(Long orderId, String callback) {
		YgOrderInfoModel model = ygOrderService.findOrderInfo(orderId);
		return new JSONPObject(callback, Message.success(model));
	}

	/**
	 * 获取退换货订单列表
	 *
	 * @param queryInfo
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findReturnList")
	@ResponseBody
	public JSONPObject findReturnList(String callback) {
		List<YgReturnOrderModel> returnOrderList = ygReturnOrderService.findReturnList(getSessionUser().getId(), 20);
		return new JSONPObject(callback, Message.success(returnOrderList));

	}

	/**
	 * 获取退换货单详细
	 *
	 * @param queryInfo
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findReturnOrderInfo")
	@ResponseBody
	public JSONPObject findReturnOrderInfo(String returnCode, String callback) {
		YgReturnOrderInfoModel orderInfo = ygReturnOrderService.findReturnOrderInfo(returnCode, getSessionUser().getId());
		return new JSONPObject(callback, Message.success(orderInfo));
	}

	/**
	 * 获取退换货进度
	 *
	 * @param queryInfo
	 * @param callback
	 * @return
	 */
	@RequestMapping("/getReturnScheduleList")
	@ResponseBody
	public JSONPObject getReturnScheduleList(String returnCode, String callback) {
		List<YgReturnOrderLog> list = ygReturnOrderLogService.findReturnScheduleList(returnCode);
		Message msg = Message.success(list);
		return new JSONPObject(callback, msg);

	}

	/**
	 * 获取欢迎语
	 *
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findWelcome")
	@ResponseBody
	public JSONPObject findWelcome(String callback) {
		return new JSONPObject(callback, quickReplyService.findWelcomeContent());
	}

	public YgUserModel getSessionUser() {
		Subject subject = SecurityUtils.getSubject();
		return (YgUserModel) subject.getPrincipal();
	}

	/**
	 * 发送推送消息给客服
	 *
	 * @throws UnsupportedEncodingException
	 */
	@WebLog("发送推送消息给客服")
	@RequestMapping("/sendAppMessage")
	@ResponseBody
	public void sendAppMessage(String appToken, String msg) throws UnsupportedEncodingException {
		/*String c = redisDao.get("APP_" + appToken);
		if (StringUtils.isNotEmpty(c)) {
			CustomerUser customer = JSON.parseObject(c, CustomerUser.class);
			msg = URLEncoder.encode(msg, "utf-8");
			ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
			String url = String.format("https://api.yiigoo.com/app/push/sendMessge.do?appType=%s&apptoken=%s&msg=%s", customer.getCreateBy(), customer.getUpdateBy(), msg);

			fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					@SuppressWarnings("resource")
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost post = new HttpPost(url);
					post.setHeader("Content-type", "application/json; charset=utf-8");
					post.setHeader("Connection", "Close");
					try {

						HttpResponse response = httpClient.execute(post);

					} catch (ClientProtocolException e) {

						e.printStackTrace();
						post.releaseConnection();

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						post.releaseConnection();
					}


				}
			});
			fixedThreadPool.shutdown();
		}*/
	}

}
